<template>
  <div class="selectQuestionView">
    <a-card class="questionList">
      <div class="header">
        <h2>{{ moduleData.title }}</h2>
      </div>
      <div class="progress-section">
        <span
          >完成度：{{ completedCount }}/{{ moduleData.questions.length }}</span
        >
        <div class="progress-bar-container">
          <div
            class="progress-bar"
            :style="{ width: progressWidth + '%' }"
          ></div>
        </div>
      </div>
      <a-form layout="inline" class="searchParams">
        <a-form-item
          field="extent"
          label="难度"
          style="width: 130px"
          class="flex-1"
        >
          <a-select
            v-model="selectedDifficulty"
            placeholder="全部"
            :style="{ width: '160px' }"
          >
            <a-option value="all" style="color: var(--color-text-2)"
              >全部</a-option
            >
            <a-option style="color: #00af9b">简单</a-option>
            <a-option style="color: #ffb800">中等</a-option>
            <a-option style="color: #ff2d55">困难</a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          field="status"
          label="状态"
          style="width: 130px"
          class="flex-2"
        >
          <a-select
            v-model="selectedStatus"
            placeholder="全部"
            :style="{ width: '160px' }"
          >
            <a-option value="all" style="color: var(--color-text-2)"
              >全部</a-option
            >
            <a-option value="unstarted" style="color: #818181">未开始</a-option>
            <a-option value="passed" style="color: #00af9b">已通过</a-option>
            <a-option value="tried" style="color: #ffb800">尝试过</a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button
            class="addTest"
            type="primary"
            @click="handleConfirm"
            :style="{ background: '#065ACC' }"
            >确认</a-button
          >
        </a-form-item>
      </a-form>
      <a-divider class="divider" />
      <a-table
        :columns="columns"
        :data="filteredQuestions"
        :pagination="{
          showTotal: true,
          hideOnSinglePage: true,
        }"
        :bordered="{ wrapper: true, cell: true }"
        stripe
      >
        <template #selected="{ record }">
          <a-checkbox
            v-model="record.selected"
            @change="toggleQuestion(record)"
          />
        </template>
        <template #status="{ record }">
          <span :class="`status ${getStatus(record)}`">{{
            getStatus(record)
          }}</span>
        </template>
        <template #title="{ record }">
          <a-link @click="toQuestionPage(record)">{{ record.title }}</a-link>
        </template>
        <template #passRate="{ record }">
          {{ record.randomAcceptNum }}/{{ record.submitNum }}
        </template>
        <template #difficulty="{ record }">
          <span :class="`difficulty ${getDifficulty(record)}`">{{
            getDifficulty(record)
          }}</span>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import axios from "axios";
import { Message } from "@arco-design/web-vue";

const store = useStore();
const router = useRouter();
const examId = ref(null); // 保存试卷id

const moduleData = ref({
  questions: [],
  title: "选择题目",
  image: "",
});
const columns = [
  {
    title: "选择",
    slotName: "selected",
  },
  {
    title: "状态",
    slotName: "status",
  },
  {
    title: "题目",
    slotName: "title",
  },
  {
    title: "通过率",
    slotName: "passRate",
  },
  {
    title: "难度",
    slotName: "difficulty",
  },
];
const selectedDifficulty = ref("all");
const selectedStatus = ref("all");

const completedCount = computed(() => {
  return moduleData.value.questions.filter((q) => q.status === "passed").length;
});

const progressWidth = computed(() => {
  return (completedCount.value / moduleData.value.questions.length) * 100;
});

const filteredQuestions = computed(() => {
  return moduleData.value.questions.filter((question) => {
    return (
      (selectedDifficulty.value === "all" ||
        question.tags.includes(selectedDifficulty.value)) &&
      (selectedStatus.value === "all" ||
        getStatus(question) === selectedStatus.value)
    );
  });
});

const fetchQuestions = () => {
  store.commit("loading/showLoading", true);
  axios
    .get("http://localhost:8121/api/questions/get/vo/all")
    .then((response) => {
      moduleData.value.questions = response.data.map((question) => ({
        ...question,
        tags: JSON.parse(question.tags),
        status: calculateStatus(question),
        submitNum: randomInt(50, 200),
        randomAcceptNum: calculateAcceptNum(
          question.tags[0],
          randomInt(50, 200),
        ),
        selected: false,
      }));
    })
    .catch((error) => console.error("获取问题时出错:", error))
    .finally(() => {
      store.commit("loading/showLoading", false);
    });
};

const calculateStatus = (question) => {
  if (question.randomAcceptNum > 0) {
    return "passed";
  } else if (question.submitNum > 0) {
    return "tried";
  } else {
    return "unstarted";
  }
};

const getDifficulty = (question) => {
  return question.tags[0];
};

const getStatus = (question) => {
  return calculateStatus(question);
};

const toQuestionPage = (question) => {
  router.push({ path: `/view/question/${question.id}` });
};

const randomInt = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

const calculateAcceptNum = (difficulty, submissions) => {
  if (difficulty === "简单") {
    return randomInt(submissions * 0.5, submissions);
  } else if (difficulty === "中等") {
    return randomInt(submissions * 0.3, submissions * 0.5);
  } else {
    return randomInt(0, submissions * 0.3);
  }
};

const toggleQuestion = async (question) => {
  try {
    // 使用axios获取最后一条试卷的ID
    const examIdResponse = await axios.get(
      "http://localhost:8121/api/examination/getLastExaminationId",
    );
    const examId = examIdResponse.data;

    const endpoint = `http://localhost:8121/api/examQuestion/toggle`;

    // 使用axios发送请求以切换题目选择状态
    await axios.post(endpoint, {
      examId,
      questionId: question.id,
      isChecked: question.selected, // 使用当前选中状态
    });
  } catch (error) {
    console.error("保存或删除题目时出错:", error.message);
    Message.error("操作过程中发生错误");
    // 请求失败时，恢复到之前的状态（回滚操作）
    question.selected = !question.selected;
  }
};

const handleConfirm = async () => {
  // 在确认选择后，将选中的题目保存到数据库，并保存试卷ID
  try {
    const examIdResponse = await axios.get(
      "http://localhost:8121/api/examination/getLastExaminationId",
    );
    examId.value = examIdResponse.data;

    // 跳转到题目展示界面并传递试卷ID
    await router.push(`/manage/test/display/${examId.value}`);
  } catch (error) {
    console.error("获取试卷ID失败:", error.message);
    Message.error("获取试卷ID失败，请重试");
  }
};

onMounted(() => {
  fetchQuestions();
});
</script>

<style scoped>
.flex-1 {
  flex: 1;
}
.flex-2 {
  flex: 2;
}
.divider {
  margin: 10px 0 20px 0;
}
.progress-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.progress-section span {
  font-size: 14px;
  color: #555;
}

.progress-bar-container {
  width: 100%;
  height: 8px;
  background-color: #ddd;
  border-radius: 4px;
  overflow: hidden;
  margin-left: 10px;
  position: relative;
}

.progress-bar {
  width: 0;
  height: 100%;
  background-color: #007bff;
}
.status {
  color: #777;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.status.unstarted::before {
  content: "—";
  color: #777;
}

.status.passed::before {
  content: "✔";
  color: green;
  font-size: 18px;
}

.status.tried::before {
  content: "⚠";
  color: orange;
  font-size: 18px;
}

.difficulty {
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 600;
}

.difficulty.简单 {
  color: #4caf50;
}

.difficulty.中等 {
  color: orange;
}

.difficulty.困难 {
  color: #f44336;
}
</style>
